<script setup>
import { ref } from 'vue'
import { userloginCodeService } from '@/api/auth'

import { captchaCodeLoginService } from '@/api/user'

import { useUserStore } from '@/stores'
import { Message, Lock } from '@element-plus/icons-vue'
import { useRouter } from 'vue-router'

const userStore = useUserStore()
const router = useRouter()

const formRef = ref()
const formModel = ref({
  email: '',
  code: ''
})

//防抖
const disabled = ref(false)

//登录
const yzmLogin = async () => {
  await formRef.value.validate()
  disabled.value = true
  try {
    const result = await userloginCodeService(formModel.value)
    // console.log('result:', result)
    await userStore.setToken(result.data)
    await userStore.getUser()
    ElMessage.success('登录成功')
    router.push('/')
  } catch (err) {
    console.error('loginError:', err)
    ElMessage.error('登录失败')
  } finally {
    formModel.value.email = ''
    formModel.value.code = ''
    disabled.value = false
  }
}

const isRegsiter = ref(false)

const rules = ref({
  code: [
    {
      required: true,
      message: '请输入验证码',
      trigger: 'blur'
    },
    {
      pattern: /^\d{6}$/,
      message: '验证码必须是6位数字',
      trigger: 'blur'
    }
  ],
  email: [
    {
      required: true,
      message: '请输入邮箱地址',
      trigger: 'blur'
    },
    {
      type: 'email',
      message: '请输入正确的邮箱地址',
      trigger: ['blur']
    }
  ]
})

const yz = ref({
  total: 60,
  curry: 60,
  timer: null
})

//发送验证码
const onSend = () => {
  //验证通过 err：true, 反之为：false
  formRef.value.validateField('email', async (err) => {
    if (err) {
      if (!yz.value.timer && yz.value.total === yz.value.curry) {
        disabled.value = true
        try {
          await captchaCodeLoginService({ email: formModel.value.email })
          ElMessage.success('验证码已发送，一分钟之内有效，请注意查收')
          //开启定时器
          yz.value.timer = setInterval(() => {
            yz.value.curry--
            if (yz.value.curry <= 0) {
              clearInterval(yz.value.timer)
              yz.value.timer = null
              yz.value.curry = yz.value.total
              disabled.value = false
            }
          }, 1000)
        } finally {
          disabled.value = false
        }
      }
    } else {
      ElMessage.error('请输入正确的邮箱地址')
      return
    }
  })
}
</script>
<template>
  <div class="login_container">
    <div class="login_box">
      <div class="box">
        <header class="header">
          <router-link to="/">
            <img style="width: 75px; height: 75px" src="@/assets/image/logo.png" alt="logo" />
          </router-link>
          <div class="text">
            宠物管家
            <p class="tesc">-- 轻松管理你的宠物 --</p>
          </div>
        </header>

        <main class="main">


          <el-form class="my_form" ref="formRef" :model="formModel" :rules="rules" autocomplete="false" size="large">
            <el-form-item prop="email">
              <el-input v-model="formModel.email" placeholder="请输入邮箱" :prefix-icon="Message" />
            </el-form-item>
            <el-form-item prop="code">
              <el-input v-model="formModel.code" placeholder="请输入验证码" :prefix-icon="Grid">
                <template #append>
                  <el-button type="primary" :disabled="disabled" @click="onSend">{{
                    yz.total === yz.curry ? '获取验证码' : yz.curry + 's后重新发送'
                    }}</el-button>
                </template>
              </el-input>
            </el-form-item>
            <el-form-item class="btn_group">
              <el-button @click.prevent="yzmLogin" class="btn" type="primary" auto-insert-space="true">登录</el-button>
              <router-link style="margin-left: auto;" to="/login">返 回</router-link>
            </el-form-item>
          </el-form>
        </main>
      </div>
      <div class="img">
        <img src="@/assets/image/bg1.jpg" alt="" />
      </div>
    </div>
  </div>
</template>
<style scoped lang="scss">
.login_container {
  background: #36D1DC;
  /* fallback for old browsers */
  background: -webkit-linear-gradient(to right, #5B86E5, #36D1DC);
  /* Chrome 10-25, Safari 5.1-6 */
  background: linear-gradient(to right, #5B86E5, #36D1DC);
  /* W3C, IE 10+/ Edge, Firefox 16+, Chrome 26+, Opera 12+, Safari 7+ */

  width: 100vw;
  height: 100vh;
  display: flex;
  justify-content: center;
  align-items: center;

  .login_box {
    box-shadow: 0 2px 16px 0 #74b4ce;
    border-radius: 20px 0 0 20px;
    display: flex;
    justify-content: space-around;

    .box {
      background-color: #fff;
      width: 25.125rem;
      padding: 2rem;
      padding-bottom: 1rem;
      letter-spacing: 2px;
      border-radius: 20px 0 0 20px;

      .header {
        display: flex;
        justify-content: center;
        margin-bottom: 1rem;

        .text {
          color: rgb(70, 174, 216);
          font-size: 1.5rem;
          margin-left: 1.5rem;
          text-align: center;

          .tesc {
            margin-top: 0.6rem;
            font-size: 0.6rem;
            color: #ccc;
          }
        }
      }

      .main {
        .btn_group {
          .btn {
            width: 45%;
          }

          .btn:first-child {
            margin-right: auto;
          }
        }
      }
    }

    .img {
      width: 28.125rem;
      overflow: hidden;

      img {
        width: 100%;
        height: 100%;
        object-fit: cover;
      }
    }
  }
}
</style>
